/*
 * @Date: 2022-08-01 14:47:52
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:启动核心服务
 * @LastEditTime: 2023-11-16 15:43:32
 * @FilePath: \go-ezcode-admin\system\init.go
 */
package system

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"runtime"
	"syscall"
	"time"

	"go-ezcode-admin/system/core/config"
	"go-ezcode-admin/system/core/db"
	"go-ezcode-admin/system/core/log"
	"go-ezcode-admin/system/core/task"
	"go-ezcode-admin/system/core/trans"
	"go-ezcode-admin/system/router"
	"go-ezcode-admin/system/util/str"
	"go-ezcode-admin/system/util/sys"
)

var basedir = sys.ExecutePath() + "\\" //根目录
func Init() {
	//在线用户Id
	//GenApiDoc()  //生成api文档
	config.InitConfig(basedir + "config.toml")

	log.Intrance() //初始化日志

	db.Instance() //初始化全局数据库单例

	db.InitSystemTables() //初始化system的数据库表
	trans.InitTrans("en") //初始化翻译

	r := router.InitRouter()

	var sHttp *http.Server
	var sHttps *http.Server
	if config.Instance().App.HttpPort != 0 {
		sHttp := &http.Server{
			Addr:           fmt.Sprintf(":%d", config.Instance().App.HttpPort),
			Handler:        r,
			ReadTimeout:    time.Duration(config.Instance().App.Timeout) * time.Second,
			WriteTimeout:   time.Duration(config.Instance().App.Timeout) * time.Second,
			MaxHeaderBytes: 1 << 20,
		}
		go func() {
			if err := sHttp.ListenAndServe(); err != nil && err != http.ErrServerClosed {
				log.Intrance().Error(err.Error())
				os.Exit(0)
			}
		}()
		fmt.Printf(`http运行地址:http://127.0.0.1:%d`, config.Instance().App.HttpPort)
	}

	if config.Instance().App.HttpsPort != 0 {

		sHttps := &http.Server{
			Addr:           fmt.Sprintf(":%d", config.Instance().App.HttpsPort),
			Handler:        r,
			ReadTimeout:    time.Duration(config.Instance().App.Timeout) * time.Second,
			WriteTimeout:   time.Duration(config.Instance().App.Timeout) * time.Second,
			MaxHeaderBytes: 1 << 20,
		}

		go func() {
			//https
			if err := sHttps.ListenAndServeTLS(basedir+"custom\\pem\\cert.pem", basedir+"custom\\pem\\key.pem"); err != nil && err != http.ErrServerClosed {
				log.Intrance().Error(err.Error())
				os.Exit(0)
			}

		}()
	}

	go task.Init() //初始化system任务服务

	shutDown(sHttp, sHttps)
}

func shutDown(s1 *http.Server, s2 *http.Server) {
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	fmt.Println("Shutdown Server ...")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sqlDB, _ := db.Instance().DB()
	err := sqlDB.Close()
	if err != nil {
		log.Intrance().Error(err.Error())
	}

	if s1 != nil {
		if err := s1.Shutdown(ctx); err != nil {
			log.Intrance().Error("Server Shutdown:"+err.Error()) 
		}
	}

	if s2 != nil {
		if err := s2.Shutdown(ctx); err != nil {
			log.Intrance().Error("Server Shutdown:"+err.Error())  
		}
	}

	fmt.Println("Server exiting")
}

//生成文档
//必须依赖 npm install apidoc -g
func GenApiDoc() {
	basedir := sys.ExecutePath()
	parentDir := str.BeforeLast(basedir, "\\") + "\\"
	//cmdline := "apidoc -c " + parentDir + "apidoc\\apidoc.json -i " + parentDir + "server\\system\\controller -o " + parentDir + "server\\apidoc -t " + parentDir + "apidoc\\template"
	cmdline := parentDir + "GenApidoc.bat"
	fmt.Println(runtime.GOOS)

	if runtime.GOOS == "windows" {
		// 执行命令，并返回结果

		cmd := exec.Command("cmd", "/c", "start "+cmdline)
		cmd.Dir = parentDir
		cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
		err := cmd.Run()
		if err != nil {
			panic(err)
		}

	}

}
